# yun-cha-coffee PyCharm
# 2025/8/30 17:55

from fastapi import APIRouter
from typing import Union,List
from app.models import *
from pydantic import BaseModel, validator

productRelation_api = APIRouter(prefix="/productRelation")

@productRelation_api.get("/",summary="查询所有产品关联表")
async def getAllProductRelations():
    # 查询所有
    productRelations = await ProductRelation.all()

    return {
        "code":200,
        "message":"查询成功",
        "data":productRelations
    }

@productRelation_api.get("/{id}",summary="查询某一个产品关联表")
async def getOneProductRelation(id:int):
    productRelation = await ProductRelation.get(id=id)

    return {
        "code":200,
        "message":"查询成功",
        "data":productRelation
    }




class ProductRelationIn(BaseModel):
    main_product_id: int  # 确保是正整数
    main_product_type: ProductTypeEnum
    related_product_id: int
    related_product_type: ProductTypeEnum
    relation_type: RelationTypeEnum
    sort_order:int
    is_active: bool
@productRelation_api.post("/")
async def addProductRelation(relation_data:ProductRelationIn):
    await ProductRelation.create(
        main_product_id=relation_data.main_product_id,
        main_product_type=relation_data.main_product_type,
        related_product_id=relation_data.related_product_id,
        related_product_type=relation_data.related_product_type,
        relation_type=relation_data.relation_type,
        sort_order=relation_data.sort_order,
        is_active=relation_data.is_active
    )

    return {
        "code":200,
        "message":"添加成功"
    }

@productRelation_api.delete("/{id}")
async def deleteProductRelation(id:int):
    await ProductRelation.filter(id=id).delete()

    return {
        "code":200,
        "message":"删除成功"
    }

@productRelation_api.put("/{id}")
async def updateProductRelation(id:int,relation_data:ProductRelationIn):
    relation_data = relation_data.dict()
    await ProductRelation.filter(id=id).update(**relation_data)

    return {
        "code":200,
        "message":"修改成功"
    }
